package com.googlecode.jpocketmod.templates;

import com.googlecode.jpocketmod.templates.pages.PocketModPageInstance;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Vector;

/**
 *
 * @author David Sosby
 */
public class PocketModTemplate implements Serializable {
	private String paperSize, description, author;
	private int rows, cols;
	private int frontIndex, backIndex;
	
	private List<PocketModPageInstance> pages;
	
	public PocketModTemplate()  {
		/* DEFAULT VALUES		 */
		setPaperSize("Letter");
		setDescription("");
		setAuthor("");
		setRows(4);
		setCols(2);
		setFrontIndex(0);
		setBackIndex(7);
		
		/* --------------        */
		
		pages = new Vector<PocketModPageInstance>(rows*cols);
		for ( int i=0 ; i<rows*cols ; i++ )  {
			pages.add(new PocketModPageInstance());
		}
	}
	
	private void setPaperSize(String paperSize)  {  this.paperSize = paperSize;  }
	public void setDescription(String description)  {  this.description = description;  }
	public void setAuthor(String author)  {  this.author = author;  }
	private void setRows(int rows)  {  this.rows = rows;  }
	private void setCols(int cols)  {  this.cols = cols;  }
	private void setFrontIndex(int index)  {  this.frontIndex = index;  }
	private void setBackIndex(int index)  {  this.backIndex = index;  }
	
	public String getDescription()  {  return description;  }
	public String getAuthor()  {  return author;  }
	public int getRows()  {  return rows;  }
	public int getCols()  {  return cols;  }
	public String getPaperSize()  {  return paperSize;  }
	
	public PocketModPageInstance getPage(int pageIndex)  {
		return pages.get(pageIndex);
	}
	
	public void setPage(PocketModPageInstance page, int pageIndex)  {
		pages.set(pageIndex, page);
	}
	
	public static PocketModTemplate loadFromFile(File templateFile) throws Exception  {
		if (templateFile.exists())  {
			FileInputStream fis = null;
			ObjectInputStream ois = null;
			
			try  {
				fis = new FileInputStream(templateFile);
				ois = new ObjectInputStream(fis);
				
				PocketModTemplate toReturn = (PocketModTemplate) ois.readObject();
				return toReturn;
			}
			catch (Exception ex)  {
				throw ex;
			}
			finally  {
				if ( fis != null )
					try { fis.close(); } catch(Exception ex) {}
				
				if ( ois != null ) 
					try { ois.close(); } catch(Exception ex) {}
			}
		}
		
		return null;
	}
	
	public static void saveToFile(PocketModTemplate template, File f) throws Exception  {
		FileOutputStream ops = null;
		
		try  {
			ops = new FileOutputStream(f);
			ObjectOutputStream out = new ObjectOutputStream(ops);
			out.writeObject(template);
			out.close();
		}
		catch (Exception ex)  {
			throw ex;
		}
		finally {
			if ( ops != null )
				try  {  ops.close();  } catch(Exception ex) {}
		}
	}
}
